package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class FilePicutreUpload extends PictureUploadTemplate {
    @Override
    protected String getMainName(Object file) {
        MultipartFile multipartFile = (MultipartFile) file;
        return multipartFile.getOriginalFilename();
    }

    @Override
    public void checkPacture(Object file) {
        MultipartFile multipartFile = (MultipartFile) file;

        //对象不能为空，如果为空返回异常
        if (file == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件不能为空");
        }
        //校验文件大小
        final long RuleSize = 1024*1024;
        long filesize = multipartFile.getSize();
        if(filesize > RuleSize){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小不能大于2M");
        }
        //校验文件格式
        final List<String> list = Arrays.asList("jdp","png");
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        if(!list.contains(suffix)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误");
        }
    }

    @Override
    public void OjbectToFile(Object file, File tempFile) throws IOException {
        MultipartFile multipartFile = (MultipartFile) file;
        multipartFile.transferTo(tempFile);
    }
}
